package com.hht;

import java.util.concurrent.CountDownLatch;

/**
 * 赛跑比赛倒计时
 * 主要用于线程等待控制 CountDownLatch 不可复用（相对 CyclicBarrier)
 * N个线程都完成后  await等待才会结束
 */
public class CountDownLatchDemo {

	public static void main(String[] args) {
		//创建一个需要多少个事件发生才可以指定线程执行的计数器，这里的3表示三个事件发生才可以执行
		CountDownLatch countDownLatch = new CountDownLatch(3);
		
		new Racer(countDownLatch, "A").start();
		new Racer(countDownLatch, "B").start();
		new Racer(countDownLatch, "C").start();
		
		for(int i=0;i<3;i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(3 - i);
			countDownLatch.countDown();
			if(i == 2) {
				System.out.println("Start");
			}
		}
	}
}

class Racer extends Thread {
	
	private CountDownLatch countDownLatch;
	
	public Racer(CountDownLatch countDownLatch, String name) {
		setName(name);
		this.countDownLatch = countDownLatch;
	}
	
	public void run() {
		try {
			countDownLatch.await();
			for(int i=0;i<3;i++) {
				System.out.println(getName() + " : " + i);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}